/**
* @(#)com.my.filter.LoginFilter.java
* 南京中兴软创科技有限责任公司
* @date 2013-10-17
*/
package com.my.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/** 
 * 
 * @author <a href="tong.hao@zte.com.cn">童浩</a>
 * @version 1.0 
 * @since 2013-10-17 下午5:07:58 
 */

public class LoginFilter implements Filter {
	
	public static Map<String, String> initUsers = new HashMap<String, String>();

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		HttpServletRequest req= (HttpServletRequest)request;
		PrintWriter writer = response.getWriter();
		// 登录拦截
		String url = req.getRequestURI();
		if(url.contains("login") || url.contains("None") || url.contains("html") || url.contains("setCookie")) {
			chain.doFilter(request, response);
			return;
		}
		//HttpSession session = req.getSession();
		//User u = (User) session.getAttribute("loginUser");
		/*if(u == null) {
			writer.println("请登录");
			return;
		} else {
			chain.doFilter(request, response);
		}*/
		
		Cookie[] cs = req.getCookies();
		if(cs != null) {
			for(Cookie c: cs) {
				System.out.println("f:" + c.getName() + "---" + c.getValue());
				if(c.getName().equals("loginUser")) {
					if(c.getValue().equals("a")) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
		}
		
		writer.println("请登录2");
		return;
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		initUsers.put("admin", "a");
		initUsers.put("tom", "a");
	}

}
